package org.rainbowinverted.charging.device.connect.ykc.server.handler;

import cn.hutool.core.util.HexUtil;
import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcChargeStandardIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcMessageIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.out.YkcChargeStandardSettingOut;
import org.rainbowinverted.charging.device.connect.ykc.server.util.DelayedExecutorUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * 计费标准设置处理器
 *
 * @author hehuaiping
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class YkcChargeStandardSettingHandler extends YkcAbstractHandler<YkcChargeStandardIn, YkcChargeStandardSettingOut> {
    @Override
    public void read(ChannelHandlerContext channel, YkcMessageIn message) {
        Long deviceNo = readDeviceNo(message.getMessageBody());
        log.info("charge standard setting deviceNo:{}", deviceNo);
    }

    @Override
    public void write(ByteBuf byteBuf, YkcChargeStandardSettingOut ykcChargeStandardOut) {
        CompletableFuture.runAsync(() -> {
            writeDeviceNo(byteBuf, ykcChargeStandardOut.getDeviceNo());
            // 固定值：0100
            byteBuf.writeBytes(HexUtil.decodeHex(String.format("%04d", ykcChargeStandardOut.getChargeStandardModelNo())));
            // 尖、峰、平、谷费用精确到五位小数
            byteBuf.writeIntLE(ykcChargeStandardOut.getSharpElectricityFee());
            byteBuf.writeIntLE(ykcChargeStandardOut.getSharpServiceFee());
            byteBuf.writeIntLE(ykcChargeStandardOut.getPeakElectricityFee());
            byteBuf.writeIntLE(ykcChargeStandardOut.getPeakServiceFee());
            byteBuf.writeIntLE(ykcChargeStandardOut.getFlatServiceFee());
            byteBuf.writeIntLE(ykcChargeStandardOut.getFlatServiceFee());
            byteBuf.writeIntLE(ykcChargeStandardOut.getValleyServiceFee());
            byteBuf.writeIntLE(ykcChargeStandardOut.getValleyServiceFee());
            for (int i = 0; i < ykcChargeStandardOut.getTimeRangeFeeRate().length; i++) {
                byteBuf.writeByte(ykcChargeStandardOut.getTimeRangeFeeRate()[i].getFeeRate());
            }
        }, DelayedExecutorUtil.getExecutor());
    }
}
